package phone.qyg.com.qyg.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.ShareOtherUtils;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.CustomVideoView;
import com.app.view.RatioFrameLayout;
import com.umeng.socialize.ShareAction;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.CollectionItem;
import phone.qyg.com.qyg.model.CultureDetail;
import phone.qyg.com.qyg.model.CultureVideo;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2018/1/10 17:04
 * 邮箱：lanbuhan@163.com
 * 功能：文化超市详情-视频
 */
@ContentView(R.layout.culture_video_detail)
public class CultureVideoDetailActivity extends BaseActivity {

    final  double VIDEO_BL = 1.7778;//视频比例

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.share)
    TextView share;

    @ViewInject(R.id.chollect)
    TextView chollect;

    @ViewInject(R.id.title)
    TextView title;

    @ViewInject(R.id.time)
    TextView time;

    @ViewInject(R.id.code)
    TextView code;

    @ViewInject(R.id.author)
    TextView author;

    @ViewInject(R.id.type)
    TextView type;

    @ViewInject(R.id.publish)
    TextView publish;

    @ViewInject(R.id.keyword)
    TextView keyword;

    @ViewInject(R.id.content)
    TextView content;

    @ViewInject(R.id.course_play)
    TextView course_play;

    @ViewInject(R.id.full_video)
    TextView full_video;

    @ViewInject(R.id.img)
    ImageView img;

    @ViewInject(R.id.recycler)
    RecyclerView recycler;

    @ViewInject(R.id.title_layout)
    RelativeLayout title_layout;

    @ViewInject(R.id.video_view)
    CustomVideoView video_view;

    @ViewInject(R.id.head_frame)
    RatioFrameLayout head_frame;

    BroadcastReceiver mNetworkReceiver;

    Timer mCheckPlayingProgressTimer;

    Uri mVideoUri;

    int mPlayingPos;

    int mLastLoadLength = -1;//断网/onStop前缓存的位置信息(ms)

    int deltaTime = 2500;

    boolean isTranVideoItem;

    ShareAction mShareAction;

    CultureDetail model;

    List<CultureVideo> videos;

    int resId;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();

        if(obj instanceof Base){
            Base base = (Base) obj;
            resId = base.id;
        }else if(obj instanceof CollectionItem){
            CollectionItem item = (CollectionItem) obj;
            resId = item.objectId;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mapKeys.put(AppHttpKey.CULTURE_RES_ID,String.valueOf(resId));

        AppHttpRequest.httpRequestDefalut(ApplicationConfig.RES_INFO_DETAIL,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            if(JSONTool.isStatus(result)){
                                model = JSONTool.jsonDefaluTranClazz(result,null, CultureDetail.class);
                                setData();
                            }else{
                                PromptManager.showToast(JSONTool.errorHint(result));
                            }
                        }else{
                            PromptManager.showToast(R.string.service_error);
                        }
                    }
                });
    }

    private void setData(){
        if(null == model) return;

        back.setText(model.title);
        title.setText(model.title);
        time.setText(addStr(R.string.appear_time,model.pubTime));
        code.setText(addStr(R.string.res_code,model.code));
        author.setText(addStr(R.string.author,model.author));
        type.setText(addStr(R.string.type,model.resClassName));
        publish.setText(addStr(R.string.publishing_unit,model.publishUnit));
        keyword.setText(addStr(R.string.keyword,model.keywords));
        content.setText(setAttributeText(model.content));

        setImgPath(model.fixImgUrl,img, OptionImageUtils.getRectRatio43());

        CommonUtil.setTextViewDrawableDirection(chollect,4,
                (model.isCollection == 0)?
                        R.drawable.title_collect_normal:
                        R.drawable.title_collect_select);

        videos =  model.videoList;

        course_play.setVisibility(isRequestList(videos)?View.VISIBLE:View.GONE);
        setVideosData(videos);
    }

    private void setVideosData(List<CultureVideo> models){
        if(!isRequestList(models))return;

        final CommonAdapter adapter = new CommonAdapter<CultureVideo>(QXApplication.getContext(),R.layout.culture_item_video,models) {
            @Override
            protected void convert(ViewHolder holder, CultureVideo model, int position) {
                String duration = model.duration;
                holder.setText(R.id.item_address,model.duration);
                holder.setText(R.id.item_title,model.title);
                holder.setImage(R.id.item_img,model.fixImgUrl,OptionImageUtils.getRectRatio43());
                holder.setVisible(R.id.item_address,(isRequestStr(duration))?true:false);
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                CultureVideo model = (CultureVideo) adapter.getData().get(position);


                /**
                 if(null != courseVideo){
                 if(null == mNetworkReceiver){
                 unregisterNetworkReceiver();
                 }

                 if(video_view.getCurrentPosition() > 1000){
                 video_view.seekTo(0);
                 }

                 play(courseVideo.videoUrl);
                 }
                 */
                if(null != model){
                    if(null == mNetworkReceiver){
                        unregisterNetworkReceiver();
                    }

                    String videoURL = model.videoUrl;
                    if((null != mVideoUri) && (isRequestStr(videoURL)) && (mVideoUri.getPath().equals(videoURL))){
                        return;
                    }
                    if(video_view.getCurrentPosition() > 1000){
                        video_view.seekTo(0);
                    }

                    if(isRequestStr(videoURL))
                        play(videoURL);
                }

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycler.addItemDecoration(new RecyclerViewItemDecoration(
                RecyclerViewItemDecoration.MODE_VERTICAL,
                getResources().getColor(R.color.divider),
                CommonUtil.dip2px(QXApplication.getContext(),10),0,0));

        recycler.setLayoutManager(layoutVerManager);
        recycler.setAdapter(adapter);
    }

    @Event(value = {R.id.back,R.id.chollect,R.id.share,R.id.course_play,R.id.full_video})
    private void viewOnClick(View v){
        if(model == null && (v != back)){
            return;
        }
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.chollect:
                if(isUserLogin()){
                    final int isCollection = model.isCollection;
                    AppHttpRequest.collection(model.id, isCollection, "3", model.title, new AppHttpRequest.OnAppHttpListener() {
                        @Override
                        public void onAppHttpState(boolean isState, String result) {
                            if(isState){
                                PromptManager.showToast((isCollection == 0)?R.string.conllection_sucess:R.string.conllection_quit_sucess);
                                model.isCollection = (isCollection == 0) ? 1:0;
                                CommonUtil.setTextViewDrawableDirection(chollect,4,(model.isCollection == 0)? R.drawable.title_collect_normal: R.drawable.title_collect_select);
                            }
                        }
                    });
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
            case R.id.share:
                mShareAction  =  ShareOtherUtils.shareTool(this,
                        model.shareAddress,
                        model.title,
                        model.content,
                        model.fixImgUrl);
                mShareAction.open();
                break;
            case R.id.course_play:
                if(!isRequestList(videos))return;
                CultureVideo video = videos.get(0);
                play(video.videoUrl);
                break;
            case R.id.full_video:
                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                    full_video.
                    CommonUtil.setTextViewDrawableDirection(full_video,4,R.drawable.video_fullscreen);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    CommonUtil.setTextViewDrawableDirection(full_video,4,R.drawable.video_nonfullscreen);
                }
                break;
        }
    }

    private void play(String videoUrl){
        if(!CommonUtil.isRequestStr(videoUrl))return;
        course_play.setVisibility(View.GONE);
        video_view.setVisibility(View.VISIBLE);

        mVideoUri= Uri.parse(videoUrl);

        MediaController mediaController = new MediaController(this);

//        video_view.setVideoURI(mVideoUri);
        video_view.setMediaController(mediaController);
        mediaController.setMediaPlayer(video_view);
        video_view.requestFocus();
//        video_view.start();

        mLastLoadLength = -1;
        mPlayingPos = -1;

        video_view.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                PromptManager.showToast(R.string.course_play_end);
                course_play.setVisibility(View.VISIBLE);
                video_view.setVisibility(View.GONE);
                full_video.setVisibility(View.GONE);

                if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }

        });

        video_view.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                SystemPrintl.systemPrintl("开始播放视频");
                isTranVideoItem = false;
            }
        });


        video_view.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int what, int i1) {
                SystemPrintl.systemPrintl("我在Error---->>>"+ what +",mPlayingPos = "+mPlayingPos);
                if ( !CommonUtil.isNetWork() ){
                    PromptManager.showToast(R.string.video_error);
                } else {
                    restartPlayVideo();
                }

                return true;
            }
        });

        registerNetworkReceiver();
    }

    /**
     * 错误时候使用
     */
    private void restartPlayVideo() {
        //todo 添加 progressBar 体验好点
        if (mCheckPlayingProgressTimer != null) {
            mCheckPlayingProgressTimer.cancel();
            mCheckPlayingProgressTimer = null;
        }
        video_view.setVideoURI(mVideoUri);
        video_view.start();
        video_view.seekTo(mPlayingPos);

        mLastLoadLength = -1;
        mPlayingPos = 0;
    }

    /**
     * 监听网络变化,用于重新缓冲
     */
    private void registerNetworkReceiver() {
        if (mNetworkReceiver == null) {
            mNetworkReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION)) {
                        doWhenNetworkChange();
                    }
                }
            };
        }
        registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }

    /**
     * 网络播放
     */
    public void doWhenNetworkChange() {

        //保存当前已缓存长度
        int bufferPercentage = video_view.getBufferPercentage();
        mLastLoadLength = bufferPercentage * video_view.getDuration() / 100;
        //这里需要判断 0
        int currentPosition = video_view.getCurrentPosition();
        if (currentPosition > 0) {
            mPlayingPos = currentPosition;
        }

        SystemPrintl.systemPrintl("缓存长度----->>>"+bufferPercentage);

        if (!CommonUtil.isNetWork()&& bufferPercentage < 100) {
            // 监听当前播放位置,在达到缓冲长度前自动停止
            if (mCheckPlayingProgressTimer == null) {
                mCheckPlayingProgressTimer = new Timer();
            }
            mCheckPlayingProgressTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mPlayingPos >= mLastLoadLength - deltaTime) {
                        video_view.pause();
                    }
                }
            }, 0, 1000);//每秒检测一次
        } else {
            restartPlayVideo();
        }
    }


    private void unregisterNetworkReceiver() {
        if (mNetworkReceiver != null) {
            unregisterReceiver(mNetworkReceiver);
        }
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
        if (video_view == null) {
            return;
        }
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().getDecorView().invalidate();
            float height = CommonUtil.getScreentWidth();
            float width = CommonUtil.getScreentHeight();
            head_frame.getLayoutParams().height = (int) width;
            head_frame.getLayoutParams().width = (int) height;
            title_layout.setVisibility(View.GONE);
        } else {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            float width = CommonUtil.getScreentWidth();
            float height = (float) (width /VIDEO_BL);
            head_frame.getLayoutParams().height = (int) height;
            head_frame.getLayoutParams().width = (int) width;
            title_layout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void initViewHandler() {

    }
}
